import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    name: 'name',
    age: 18,
  },
  getters: {
    nameFall: state => `${state.name} is Lee`,
  },
  // 只能同步
  mutations: {
    changeAge(state, payload) {
      state.age = payload.age;
    },
  },
  // 可以异步
  actions: {
    actionsChangeAge(context) {
      context.dispatch('actionsA', { payload: 'payload' });
    },
    actionsA(context, payload) {
      console.log('payload', payload);
      context.commit('changeAge', {
        age: 'from actions',
      });
    },
  },
  modules: {
    one: {
      namespaced: true,
      state: {
        name: 'one',
        age: 1,
      },
      getters: {
        namea: state => `${state.name} is Lee`,
      },
      // 只能同步
      mutations: {
        changeAge(state, payload) {
          state.age = payload.age;
        },
      },
      // 可以异步
      actions: {
        actionsChangeAge(context) {
          context.dispatch('actionsA', { payload: 'payload' });
        },
        actionsA(context, payload) {
          console.log('payload', payload);
          context.commit('changeAge', {
            age: 'from actionsA',
          });
        },
      },
    },
    two: {
      state: {
        name: 'two',
        age: 2,
      },
      getters: {
        namea: state => `${state.name} is Lee`,
      },
      // 只能同步
      mutations: {
        changeAge(state, payload) {
          state.age = payload.age;
        },
      },
      // 可以异步
      actions: {
        actionsChangeAge(context) {
          context.dispatch('actionsA', { payload: 'payload' });
        },
        actionsA(context, payload) {
          console.log('payload', payload);
          context.commit('changeAge', {
            age: 'from actionsb',
          });
        },
      },
    },
  },
});
